import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, Space, Tag, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { QuestionListItem, QuestionType, DifficultyLevel } from '@/types/question';
import { questionService } from '@/services/questionService';

const { Option } = Select;

interface QuestionSelectorProps {
  onSelect: (questions: QuestionListItem[]) => void;
  excludeIds?: number[];  // 已选择的题目ID，不显示
}

const QuestionSelector: React.FC<QuestionSelectorProps> = ({ onSelect, excludeIds = [] }) => {
  const [loading, setLoading] = useState(false);
  const [questions, setQuestions] = useState<QuestionListItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<QuestionType | undefined>();
  const [difficultyFilter, setDifficultyFilter] = useState<DifficultyLevel | undefined>();

  // 加载题目
  const fetchQuestions = async (page = 1) => {
    setLoading(true);
    try {
      const response = await questionService.getQuestions({
        page,
        limit: pagination.pageSize,
        keyword: searchKeyword || undefined,
        type: typeFilter,
        difficulty: difficultyFilter,
      });
      const data = response.data.data;
      // 过滤掉已选择的题目
      const filteredQuestions = data.results.filter(q => !excludeIds.includes(q.id));
      setQuestions(filteredQuestions);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchQuestions(1);
  }, [typeFilter, difficultyFilter]);

  // 确认选择
  const handleConfirm = () => {
    const selected = questions.filter(q => selectedRowKeys.includes(q.id));
    onSelect(selected);
  };

  // 题型映射
  const questionTypeMap: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    composite: '综合题',
  };

  // 难度映射
  const difficultyMap: Record<number, { text: string; color: string }> = {
    1: { text: '非常简单', color: 'green' },
    2: { text: '简单', color: 'blue' },
    3: { text: '中等', color: 'orange' },
    4: { text: '困难', color: 'red' },
    5: { text: '非常困难', color: 'purple' },
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '题目',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string) => text || '(无标题)',
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color="cyan">{questionTypeMap[type]}</Tag>
      ),
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 100,
      render: (difficulty: number) => {
        const config = difficultyMap[difficulty];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }} wrap>
        <Input
          placeholder="搜索题目"
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
          onPressEnter={() => fetchQuestions(1)}
          prefix={<SearchOutlined />}
          style={{ width: 200 }}
        />

        <Select
          placeholder="题型"
          style={{ width: 120 }}
          allowClear
          value={typeFilter}
          onChange={setTypeFilter}
        >
          <Option value="single_choice">单选题</Option>
          <Option value="multiple_choice">多选题</Option>
          <Option value="true_false">判断题</Option>
          <Option value="fill_blank">填空题</Option>
          <Option value="composite">综合题</Option>
        </Select>

        <Select
          placeholder="难度"
          style={{ width: 120 }}
          allowClear
          value={difficultyFilter}
          onChange={setDifficultyFilter}
        >
          <Option value={1}>非常简单</Option>
          <Option value={2}>简单</Option>
          <Option value={3}>中等</Option>
          <Option value={4}>困难</Option>
          <Option value={5}>非常困难</Option>
        </Select>

        <Button type="primary" onClick={() => fetchQuestions(1)}>
          搜索
        </Button>
      </Space>

      <Table
        columns={columns}
        dataSource={questions}
        rowKey="id"
        loading={loading}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          onChange: (page) => {
            setPagination({ ...pagination, current: page });
            fetchQuestions(page);
          },
        }}
      />

      <div style={{ marginTop: 16, textAlign: 'right' }}>
        <Space>
          <span>已选择 {selectedRowKeys.length} 道题</span>
          <Button 
            type="primary" 
            onClick={handleConfirm}
            disabled={selectedRowKeys.length === 0}
          >
            确认添加
          </Button>
        </Space>
      </div>
    </div>
  );
};

export default QuestionSelector;

